#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    int numJewelsInStones(string jewels, string stones) {
        sort(jewels.begin(), jewels.end(), greater<char>());
        sort(stones.begin(), stones.end(), greater<char>());

        int Ssmall = 0;
        for (int i = 0; i < stones.size(); i++)
        {
            if (i == stones.size() || stones[i] >= 'a')
            {
                Ssmall = i;
                break;
            }
        }
        int Jsmall = 0;
        for (int i = 0; i < jewels.size(); i++)
        {
            if (i == jewels.size() || jewels[i] >= 'a')
            {
                Jsmall = i;
                break;
            }
        }
        //cout << Ssmall << " " << Jsmall << endl;
        int count = 0;
        int flag = 0;
        for (int i = 0; i < Ssmall; i++)
        {
            //cout << i <<endl;
            if (i > 0 && flag && stones[i] == stones[i - 1])
            {
                ++count;
                continue;
            }
            else
            {
                flag = 0;
            }
            for (int j = 0; j < Jsmall; j++)
            {
                //cout << i << " " << j << endl;
                if (stones[i] == jewels[j])
                {
                    ++count;
                    flag = 0;
                    break;
                }
            }
        }

        flag = 0;
        if (Ssmall >= stones.size() || Jsmall >= jewels.size())
        {
            return count;
        }
        for (int i = Ssmall; i < stones.size(); i++)
        {
            if (flag && stones[i] == stones[i - 1])
            {
                ++count;
                continue;
            }
            else
            {
                flag = 0;
            }
            for (int j = Jsmall; j < jewels.size(); j++)
            {
                if (stones[i] == jewels[j])
                {
                    ++count;
                    flag = 0;
                }
            }
        }

        return count;
    }
};